package fr.enseirb.mycub.json;

import java.util.Date;

import fr.enseirb.mycub.PrefManager;
import fr.enseirb.mycub.service.UpdateService;
import fr.enseirb.mycub.utils.DetachableResultReceiver;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

public abstract class JSONHandler {

	protected String preference_key_last_update_date;
	public String preference_key_interval_between_update;
	protected String preference_key_interval_adress;
	
	public long preference_key_interval_between_update_default = 0L;
	
	public Context context;
	private boolean isRunning = false;
	private static long last_update_date;
	
	public static double latitude = 1337; // default value so that we don't query if not initialised
	public static double longitude = 1337;
	
	public JSONHandler(Context context){
		this.context = context;
	}
	
	public abstract boolean updateLocalDatabase(String json);
	/**
	 * 
	 * @return true if update is required since data is potentially outdated	
	 */
	protected boolean isUpdateRequired(){
		long lastUpdateLong = PrefManager.mgr.getLong(preference_key_last_update_date, 0);
		lastUpdateLong = Math.max(last_update_date, lastUpdateLong);
		
		long intervalBetweenUpdateLong = PrefManager.mgr.getLong(preference_key_interval_between_update, preference_key_interval_between_update_default);

		long nowLong = System.currentTimeMillis();
		long timeBetweenUpdate = nowLong - lastUpdateLong;
		Log.i("UPDATE required ???", " last update interval in ms : "+timeBetweenUpdate);
		//we need to update if our data is "outdated" ( expired the update interval time range )
		return timeBetweenUpdate > intervalBetweenUpdateLong;
	}
	
	/**
	 * Start a soft update if possible else a full Update if not applicable
	 * @return true if requires full update since softUpdate failed else false
	 */
	protected abstract void standardUpdate();
	
	public void taskDone(){
		isRunning = false;
	}
	
	public void registerLastUpdateDate(){
		last_update_date = System.currentTimeMillis();
		PrefManager.edit.putLong(preference_key_last_update_date, System.currentTimeMillis());
		PrefManager.edit.commit();
		Looper.prepare();
		DetachableResultReceiver receiver = DetachableResultReceiver.getInstance(new Handler());
		//TODO do specific updates
		Log.i("JSON HANDLER", "update time registered ");
		receiver.send(UpdateService.STATUS_UPDATED, null);
	}
	
	/**
	 * 
	 * @param forced true if need an update even we updated recently
	 */
	
	public void update(boolean forced){
		if(isRunning){
			Log.i("UpdateService", "task ALREADY RUNNING");
			return; //task already running.
		}
		Log.i("UpdateService", "update");
		if(isUpdateRequired() || forced ){
			isRunning = true;
			Log.i("UpdateService", "standardUpdate");
			standardUpdate();
		}
	}

}
